<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :before-upload="beforeUpload"
      :auto-upload="false"
      :on-change="onChange"
      ref="upload"
      :http-request="requests"
      :on-progress="onProgress"
      :limit="upConfig.limit"
      :file-list="upConfig.fileList"
    >
      <template #trigger>
        <slot name="trigger">
          <el-button size="small" type="primary">{{
            upConfig.btnname
          }}</el-button>
        </slot>
      </template>
      <el-button
        style="margin-left: 10px"
        size="small"
        type="success"
        v-if="false"
        @click="submitUpload"
        >upload to server</el-button
      >
      <template #tip>
        <slot name="tip"> </slot>
      </template>
    </el-upload>
  </div>
</template>

<script>
export default {
  setup() {
    return {};
  },
  props: {
    url: {
      type: String,
      required: true,
    },
    upConfig: {
      type: Object,
      default: (val1, val2) => {
        return {
          btnname: '点击上传',
          limit: 1,
          fileList: [],
        };
      },
    },
  },
  data() {
    return {};
  },
  methods: {
    //   调用此方法才可以正常上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    onChange(val, val1) {
      console.log(val);
    },

    requests(val, val1) {
      let fileObj = val.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append('file', fileObj); // 文件对象
      this.$request.post({
        url: this.url,
        header: {
          'Content-type': 'multipart/form-data',
        },
        data: fd,
        done: res => {
          if (res.code == 0) {
            //   成功回调
            this.$emit('uploadSuccess', res);
          } else {
            //   失败回调
            this.$emit('uploadFail', res);
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
